package com.alongstudio.account.commons.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alongstudio.account.commons.utils.SystemConfigUtil;
import com.alongstudio.account.constants.PropertyKeyConstant;
import com.alongstudio.account.constants.SystemConstant;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession httpSession = httpRequest.getSession();
		// 如果处于登录状态，放行
		boolean isGoOn = false;
//		String uri = httpRequest.getRequestURI();
//		System.out.println(uri);
		String reqPath = httpRequest.getServletPath();
		System.out.println(reqPath);
		boolean isNotAuthorityPage=isNotAuthorityPage(reqPath);
		if(isNotAuthorityPage){
			isGoOn = true;
		}else{
			if (httpSession.getAttribute(SystemConstant.SESSION_USER_NAME) != null) {
				if(reqPath.endsWith("jsp")){
//				String clientRedirectHome=
					httpResponse.sendRedirect(httpRequest.getContextPath() + "/showHomePage.do");
					return;
				}
				isGoOn = true;
			}
			else{
				request.setAttribute(SystemConstant.REQUEST_RE_LOGIN_FLAG, SystemConstant.REQUEST_RE_LOGIN_FLAG_TRUE);
			}
		}
		// 如果是不受权限的页面，则通过
		
		if (isGoOn) {
			chain.doFilter(request, response);
		}
		else {
			// 未登录，也不是访问登录页面或提交登录请求，故转向登录页面
			String clientRedirectPage = SystemConfigUtil.getInstance().getProperty(
					PropertyKeyConstant.CLIENT_REDIRECT_LOGIN_PAGE);
			httpResponse.sendRedirect(httpRequest.getContextPath() + clientRedirectPage);
		}
	}
	
	/**
	 * 判断页面是否是不需管控可以直接访问的
	 * @param page
	 * @return
	 */
	private boolean isNotAuthorityPage(String page){
		boolean isGoOn=false;
		String notAuthorityPages = SystemConfigUtil.getInstance().getProperty(PropertyKeyConstant.NOT_AUTHORITY_PAGES);
		String[] notAuthPagesArr = notAuthorityPages.split(";");
		for (String path : notAuthPagesArr) {
			if (page.equals(path)) {
				isGoOn = true;
				break;
			}
		}
		return isGoOn;
	}
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
